package com.gklyj.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gklyj.pojo.User;
import com.gklyj.pojo.user_zhanghao;
//import com.gklyj.pojo.User_zhanghao;
import com.gklyj.pojo.Zhanghao;
import com.gklyj.service.userService;
import com.gklyj.service.user_zhanghaoService;
import com.gklyj.service.zhanghaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;;

@Controller
@Transactional  //事务回滚
//@RestController
//@RequestMapping("/logins")
public class LoginController {

    @Autowired
    private zhanghaoService zhanghaoService;

    @Autowired
    private userService userService;

    @Autowired
    private user_zhanghaoService user_zhanghaoService;
    /*
        跳转登录页面
     */
    @GetMapping("/tologin")
    public String tologinPage(HttpServletRequest request) throws RuntimeException{
        //session.setAttribute("username",null);
        request.getSession().setAttribute("username",null);
        return "login/login";
    }

    /*
        登陆验证
     */
    @PostMapping(value = "/logins")
    @ResponseBody  //Controller 方法少 @ResponseBody 注释，无法将 Boolean 类型的数据传到前台。
    public Zhanghao loginPage(@RequestBody Zhanghao zhanghao, HttpServletRequest request) throws RuntimeException{
        //根据网页传来的数据查找数据库有无该数据
        Zhanghao user;
        user = zhanghaoService.findZhangHao(zhanghao);

        System.out.println(user);
        //System.out.println(user.getPassword());

        //账号验证成功时，user中有数据，向前端返回该数据，否则返回null
        if(user != null)
        {
            //将username存在session中
            //session.setAttribute("user",user.getUsername());
            request.getSession().setAttribute("username",zhanghao.getUsername());
            return user;
        }
        else {
            return null;
        }
    }

    /*
        注册账号
     */
    @PostMapping("/register")
    @ResponseBody
    public String toregister(@RequestBody String data) throws RuntimeException{

        //前台传入的数据先分割，转化为json数据
        System.out.println(data);
        String[] s = data.split("/");
        JSONObject json1 = JSONObject.parseObject(s[0]);
        Zhanghao zhanghao = new Zhanghao();
        zhanghao.setUsername((String) json1.get("username"));
        zhanghao.setPassword((String) json1.get("password"));
        zhanghao.setRole((String) json1.get("role"));

        JSONObject json2 = JSONObject.parseObject(s[1]);
        User user = new User();
        user.setName((String) json2.get("name"));
        Integer integer = Integer.valueOf((String) json2.get("age"));
        user.setAge(integer );
        user.setSex((String) json2.get("sex"));
        user.setGrade((String) json2.get("grade"));
        user.setMajor((String) json2.get("major"));
        user.setPhone_number((String) json2.get("phone_number"));
        user.setStu_id((String) json2.get("stu_id"));
        user.setDepartment((String) json2.get("department"));

        if (zhanghaoService.findZhangHao(zhanghao) != null){
            return "该账号已注册";
        }else {
            boolean save = zhanghaoService.save(zhanghao);
            boolean save1 = userService.save(user);

            //数据插入成功后，链接两数据
            if (save && save1){
                Integer z_id = zhanghaoService.findZ_id(zhanghao.getUsername(),zhanghao.getPassword());
                Integer u_id = userService.findU_id(user.getName(),user.getPhone_number());
                user_zhanghao uz = new user_zhanghao();
                uz.setU_id(u_id);
                uz.setZ_id(z_id);
                if(user_zhanghaoService.save(uz)){
                    return "注册成功";
                }else {
                    return "服务器异常！请重试。";
                }

            }
        }
        return "服务器异常！请重试。";
    }


    /*
        根据不同账号密码验证登录用户角色，跳转不同首页
     */
    @GetMapping("/toindex")
    public ModelAndView toindexPage(HttpServletRequest httpServletRequest) throws RuntimeException{
        Object username = httpServletRequest.getSession().getAttribute("username");
        String name = userService.findNameByUsername((String) username);
        String role = zhanghaoService.findRoelbyUsername((String) username);
        //System.out.println("--------------------------"+role);

        ModelAndView modelAndView = new ModelAndView();
        //根据不同角色跳转不同主页
        if (role.equals("student")){
            modelAndView.setViewName("qiuzhi/qz-index");
        }else if(role.equals("recruiter")){
            modelAndView.addObject("name",name);
            modelAndView.setViewName("zhaoping/zp-index");
        }else {
            modelAndView.setViewName("administer/index");
        }
        return modelAndView;
    }

    /*
    获取登录的用户姓名，用于显示登录的用户
     */
    @PostMapping("/getusername")
    public void getUsername(HttpServletRequest request, HttpServletResponse response)throws Exception{
        //先从session中获取到之前存在session中的用户信息，然后通过ObjectMapper输出返回一个json数据给html页面，由页面去解析这个json数据
        String username= (String) request.getSession().getAttribute("username");
        String name = userService.findNameByUsername(username);
        User user = new User();
        user.setName(name);
        if(user!=null){
            ObjectMapper objectMapper=new ObjectMapper();
            objectMapper.writeValue(response.getOutputStream(),user);
        }
    }

    //退出登录
    @GetMapping("/loginOut")
    public String loginOut(HttpServletRequest request){
        request.getSession().setAttribute("username",null);
        return "login/login";
    }

}
